import { createSlice,type PayloadAction } from '@reduxjs/toolkit'

//商品类型
export interface IGood{
    gid:number,
    title:string,
    price:number,
    number:number
}

//购物车 store 的 state 类型
interface ICartState{
    totalNumber:number,
    totalPrice:number,
    goods:Array<IGood>
}

//初始化值
const initialState:ICartState = {
    totalNumber:2,
    totalPrice:200,
    goods:[
        {gid:1,title:'iphone 16 pro max',price:120,number:1},
        {gid:2,title:'huawei meta 90',price:80,number:1}
    ]
}

const cartSlice = createSlice({
    name:'cart',
    //state 初始化值
    initialState,
    reducers:{
        //action 
        // 没有参数的方法
        incrCart(state){
            state.totalNumber++;
        },
        //有参数的方法
        addCart(state,action:PayloadAction<IGood>){
            //新增
            state.goods.push(action.payload)
            //修改
            state.totalNumber += action.payload.number
            state.totalPrice += (action.payload.number * action.payload.price)
        },
        //有参数的方法
        delCart(state, action: PayloadAction<number>) {
            let gd = state.goods.filter(v => v.gid == action.payload)[0]
            //反向筛选
            state.goods = state.goods.filter(v => v.gid != action.payload)
            //修改
            state.totalNumber -= gd.number
            state.totalPrice -= (gd.number * gd.price)
        }
    }
})

//导出
export const { incrCart, addCart, delCart}  = cartSlice.actions
export default cartSlice.reducer
